/*
 * Copyright (C) 2007 ETH Zurich
 *
 * This file is part of Fosstrak (www.fosstrak.org).
 *
 * Fosstrak is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software Foundation.
 *
 * Fosstrak is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Fosstrak; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */
package com.qf.cx.simplenms.subscriber.type;

import java.net.URI;
import java.net.URISyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qf.cx.simplenms.report.model.Report;
import com.qf.cx.simplenms.subscriber.type.exception.InvalidURIException;

/**
 * send message using a standard TCP socket.
 * @author swieland
 */
public class TCPSubscriberOutputChannel extends AbstractSocketSubscriberOutputChannel {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private URI uri;
	private final String host;
	private final int port;

	public TCPSubscriberOutputChannel(String notificationURI) throws InvalidURIException {
		try {
			uri = new URI(notificationURI);
			host = uri.getHost();
			port = uri.getPort();
			if (!("TCP".equalsIgnoreCase(uri.getScheme()))) {
				logger.error("invalid scheme: " + uri.getScheme());
				throw new InvalidURIException("invalid scheme: " + uri.getScheme());
			}
		} catch (URISyntaxException e) {
			logger.error("malformed URI");
			throw new InvalidURIException("malformed URI: ", e);
		}
	}

	@Override
	public boolean push(Report report) {
		logger.debug("Write reports '" + report + "' as xml to tcp socket '" + getHost() + ":" + getPort() + "'.");
		writeToSocket(getJson(report));
		return true;
	}

	@Override
	public String getHost() {
		return host;
	}

	@Override
	public int getPort() {
		return port;
	}

	@Override
	public String toString() {
		return uri.toString();
	}

}
